import React, { useEffect, Fragment } from 'react';
import { connect } from 'dva';
import { Icon, Button } from 'antd';
import {
  Form,
  FormItem,
  createFormActions,
  FormEffectHooks,
  InternalFieldList as FieldList,
} from '@formily/antd';
import { Radio } from '@formily/antd-components';
import classNames from 'classnames';

import throttle from 'lodash/throttle';
import has from 'lodash/has';
import get from 'lodash/get';
import ComboModal from './ComboModal';
import styles from '../../styles.less';

const actions = createFormActions();
const { onFormInputChange$ } = FormEffectHooks;

function ForButtonGroup({ dispatch, current }) {
  useEffect(() => {
    // 清空状态
    actions.reset({ validate: false });

    // 剔除holder是冗余的key
    const keys = Object.keys(actions.getFormGraph()).filter(val => val !== '');

    // 遍历，给所有的formItem设置值
    keys.forEach(value => {
      if (has(current, value)) {
        actions.setFieldValue([value], get(current, value));
      }
    });
  }, [current]);

  return (
    <Form
      className={classNames(styles.configForm)}
      actions={actions}
      colon={false}
      effects={() => {
        // 只监控人工操作引起的FormItem值变化
        onFormInputChange$().subscribe(
          throttle(
            async () => {
              await actions.validate({ silent: true });
              // actions.getFormState().valid取到的结果是异步的，所以必须用到await actions.validate才能得到精确的结果
              const isValid = actions.getFormState().valid;

              // 校验失败
              if (!isValid) {
                return;
              }

              dispatch({
                type: 'formDesigner/updateNode',
                payload: actions.getFormState().values,
              });
            },
            300,
            { trailing: true, leading: false }
          )
        );
      }}
    >
      <FormItem
        label="对齐方式"
        name="textAlign"
        triggerType="onChange"
        component={Radio.Group}
        dataSource={[
          { label: '左', value: 'left' },
          { label: '中', value: 'center' },
          { label: '右', value: 'right' },
        ]}
        initialValue="left"
      />

      {/* <FormItem
        label={
          <>
            是否下拉
            <Tooltip title="按钮超过4个，将以下拉方式展示">
              <Icon type="info-circle" className={styles.helpIcon} />
            </Tooltip>
          </>
        }
        name="isDropdown"
        triggerType="onChange"
        component={Switch}
        initialValue={false}
      /> */}

      <FieldList name="group">
        {({ state, mutators }) => {
          const onRemove = index => mutators.remove(index);
          const onMoveUp = index => mutators.moveUp(index);
          const onMoveDown = index => mutators.moveDown(index);
          return (
            <Fragment>
              <ComboModal
                value={state.value}
                modalProps={{
                  onOk: selectedRows => {
                    dispatch({
                      type: 'formDesigner/updateNode',
                      payload: { ...actions.getFormState().values, group: selectedRows },
                    });

                    actions.setFieldValue('group', selectedRows);
                  },
                  title: '选择按钮',
                }}
                tableProps={{
                  url: 'pmc/pcms/formVersion/buttons',
                  method: 'post',
                  multiple: true,
                  searchPlaceholder: '请输入按钮名称',
                  params: {},
                  columns: [
                    {
                      title: '按钮名称',
                      dataIndex: 'label',
                      ellipsis: true,
                    },
                    {
                      title: '视图名称',
                      dataIndex: 'viewTitle',
                      ellipsis: true,
                    },
                    {
                      title: '视图地址',
                      dataIndex: 'viewUrl',
                      ellipsis: true,
                    },
                  ],
                  rowKey: 'label',
                  label: 'label',
                  filterScope: 'label',
                }}
              />

              {state.value.map((item, index) => (
                // eslint-disable-next-line react/no-array-index-key
                <div key={index} className="margin-top">
                  <Button
                    type="dashed"
                    className="text-ellipsis"
                    style={{ width: 100 }}
                    title={item.label}
                  >
                    {item.label}
                  </Button>

                  <Icon
                    type="up-circle"
                    className="margin-left"
                    onClick={() => {
                      onMoveUp(index);
                    }}
                  />

                  <Icon
                    type="down-circle"
                    className="margin-left"
                    onClick={() => {
                      onMoveDown(index);
                    }}
                  />

                  <Icon
                    type="close-circle"
                    className="margin-left"
                    onClick={() => {
                      onRemove(index);
                    }}
                  />
                </div>
              ))}
            </Fragment>
          );
        }}
      </FieldList>
    </Form>
  );
}

export default connect(({ formDesigner }) => ({
  current: formDesigner.current,
}))(ForButtonGroup);
